package com.flow.modules.dingtalk.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.flow.common.utils.Result;
import com.flow.modules.dingtalk.service.DingTalkInitDeptAndUsersService;
import com.flow.modules.dingtalk.service.DingTalkService;
import com.flow.modules.sys.entity.SysUserEntity;
import com.flow.modules.sys.service.SysDeptService;
import com.flow.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuledong
 * @description: TODO
 * @date 2023/4/23 15:32
 */
@Slf4j
@Service
public class DingTalkInitDeptAndUsersServiceImpl implements DingTalkInitDeptAndUsersService {

    @Autowired
    private DingTalkService dingTalkService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Result synchronousDeptAndUsers() {
        Result result = new Result();
        List<Long> deptList = new ArrayList<>();
        //逐级获取部门信息列表并保存
        try{
            String accessToken = dingTalkService.getAccessToken();
            //保存部门及用户
            getDeptList(accessToken, 1L);
            return result.ok(deptList);

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * save dept and user
     * @param accessToken
     * @param deptId
     * @return
     */
    public void getDeptList(String accessToken, Long deptId){
        try {
            OapiV2DepartmentListsubResponse deptListByAccessToken = dingTalkService.getDeptListByAccessToken(accessToken, deptId);
            //获取下级部门
            if(deptListByAccessToken.getResult().size() > 0){
                List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponseList = deptListByAccessToken.getResult();
                if(deptBaseResponseList != null && !deptBaseResponseList.isEmpty()){
                    deptBaseResponseList.stream().forEach(deptBaseResponse ->{
                        // TODO 存部门 以后再补
                        log.info(deptBaseResponse.getDeptId()+"--"+deptBaseResponse.getParentId()+"--"+deptBaseResponse.getName());
                        getUserInfoByDepId(accessToken,deptBaseResponse.getDeptId());
                        //开递归
                        getDeptList(accessToken,deptBaseResponse.getDeptId());
                    });
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    private void getUserInfoByDepId(String accessToken, Long deptId) {
        try {
            Boolean hasMore = false;

            OapiV2UserListResponse userInfoByDepts = dingTalkService.getUserInfoByDepts(accessToken, deptId, 0L, 10L);
            if(userInfoByDepts.isSuccess()){
                OapiV2UserListResponse.PageResult result = userInfoByDepts.getResult();
                List<OapiV2UserListResponse.ListUserResponse> list = result.getList();
                if (CollectionUtils.isNotEmpty(list)) {
                    saveDingDingUser(list);

                    hasMore = result.getHasMore();
                    while (hasMore){
                        userInfoByDepts = dingTalkService.getUserInfoByDepts(accessToken,deptId,result.getNextCursor(),10L);
                        if(userInfoByDepts.isSuccess()){
                            result = userInfoByDepts.getResult();
                            list = result.getList();
                            saveDingDingUser(list);
                            hasMore = result.getHasMore();
                        }
                    }
                }else{
                    log.info("当前部门下无人员信息");
                }
            }else{
                log.info("接口错了");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 处理DingDing同步USER
     * @param list
     */
    private void saveDingDingUser(List<OapiV2UserListResponse.ListUserResponse> list) {
        try{
            SysUserEntity sysUser = new SysUserEntity();
            list.forEach(user->{
                log.info(user.getUserid()+"----"+user.getName()+"---"+user.getUnionid());
                // TODO 存用户 以后再补
    //            String userid = user.getUserid();
    //            //判断是否插入了
    //
    //            //上数据
    //            sysUser.setDingUserId(user.getUserid());
    //            sysUser.setUnionid(user.);

            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
